//
//  XDInputView.m
//  kabu
//
//  Created by XiangDongMBP on 2017/3/10.
//  Copyright © 2017年 East. All rights reserved.
//

#import "XDInputView.h"
#import "SZTextView.h"
#import <YYKeyboardManager.h>
#import <Masonry.h>
#import "UIColor+XDHex.h"

@interface XDInputView ()<YYKeyboardObserver, UITextViewDelegate>

@property (nonatomic, strong) SZTextView *textView;
@property (nonatomic, strong) UIView *bottomBgView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *sendBtn;

@end

@implementation XDInputView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initSubViews];
    }
    return self;
}

- (void)dealloc {
    [[YYKeyboardManager defaultManager] removeObserver:self];
}

//// tell UIKit that you are using AutoLayout
//+ (BOOL)requiresConstraintBasedLayout {
//    return YES;
//}
//
//// this is Apple's recommended place for adding/updating constraints
//- (void)updateConstraints {
//    
//    // --- remake/update constraints here
//    [self.button remakeConstraints:^(MASConstraintMaker *make) {
//        make.width.equalTo(@(self.buttonSize.width));
//        make.height.equalTo(@(self.buttonSize.height));
//    }];
//    
//    //according to apple super should be called at end of method
//    [super updateConstraints];
//}
//
//- (void)didTapButton:(UIButton *)button {
//    // --- Do your changes ie change variables that affect your layout etc ---
//    self.buttonSize = CGSize(200, 200);
//    
//    // tell constraints they need updating
//    [self setNeedsUpdateConstraints];
//}

- (void)initSubViews {
    [[YYKeyboardManager defaultManager] addObserver:self];
    
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    self.frame = [UIScreen mainScreen].bounds;

    [self.bottomBgView addSubview:self.lineView];
    [self.bottomBgView addSubview:self.textView];
    [self.bottomBgView addSubview:self.sendBtn];
    [self addSubview:self.bottomBgView];
    
    [self.bottomBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.mas_leading);
        make.trailing.equalTo(self.mas_trailing);
        make.bottom.equalTo(self.mas_bottom);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bottomBgView.mas_top);
        make.leading.equalTo(self.bottomBgView.mas_leading);
        make.trailing.equalTo(self.bottomBgView.mas_trailing);
        make.height.equalTo(@(1));
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bottomBgView.mas_top).with.offset(8);
        make.leading.equalTo(self.bottomBgView.mas_leading).with.offset(13);
        make.bottom.equalTo(self.bottomBgView.mas_bottom).with.offset(-8);
        make.trailing.equalTo(self.sendBtn.mas_leading);
        make.height.greaterThanOrEqualTo(@(33));
    }];
    
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.greaterThanOrEqualTo(self.bottomBgView.mas_top).with.offset(8);
        make.bottom.equalTo(self.textView.mas_bottom);
        make.trailing.equalTo(self.bottomBgView.mas_trailing);
        make.width.equalTo(@(60));
    }];
}

- (void)showInView:(UIView *)view {
    if (self.superview) {
        return;
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
//    CGRect viewFrame = [view convertRect:view.bounds toView:nil];
//    __block CGRect frame = self.tableView.frame;
//    frame.origin.x = CGRectGetMinX(viewFrame) + (CGRectGetWidth(viewFrame) - CGRectGetWidth(frame)) / 2.0 ;
//    frame.origin.y = CGRectGetMaxY(viewFrame);
//    self.tableView.frame = frame;
//    
//    // 选中某一个cell
//    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    
//    [self.textView becomeFirstResponder];
    
    [UIView animateWithDuration:0.2 animations:^{
        //        frame.origin.x = CGRectGetMinX(viewFrame) - self.imageViewWidth;
        //        frame.size.width = self.imageViewWidth;
        //        self.bgImageView.frame = frame;
        self.alpha = 1;
    } completion:^(BOOL finished) {
        ;
    }];
}

- (void)hideWithAnimation:(BOOL)animate {
    
    [self.textView resignFirstResponder];
    
    CGFloat duration = animate ? 0.2 : 0.0;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:duration animations:^{
        //        CGRect frame = weakSelf.bgImageView.frame;
        //        frame.origin.x = CGRectGetMaxX(frame);
        //        frame.size.width = 0;
        //        weakSelf.bgImageView.frame = frame;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

- (void)dismiss {
    [self hideWithAnimation:YES];
}

////- (void)buttonTapped:(UIButton *)button {
////    if ([self.delegate respondsToSelector:@selector(eTChSeaSelView:clickedButtonAtIndex:)]) {
////        [self.delegate eTChSeaSelView:self clickedButtonAtIndex:button.tag];
////    }
////    [self hideWithAnimation:YES];
////}
//
//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//
//    //    for (UIButton * button in self.buttonArray) {
//    //        if ([button pointInside:point withEvent:event]) {
//    //            return button;
//    //        }
//    //    }
//
//    UIView * hitView = [super hitTest:point withEvent:event];
//    if ([hitView isKindOfClass:[UITextView class]]) {
//        return hitView;
//    } else if ([hitView isKindOfClass:[UIButton class]]) {
//        return hitView;
//    }
//
//    [self hideWithAnimation:YES];
//    return nil;
//}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self hideWithAnimation:YES];
}

#pragma mark - @protocol YYKeyboardObserver
- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
    [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
        CGRect kbFrame = [[YYKeyboardManager defaultManager] convertRect:transition.toFrame toView:self];
//        CGRect textframe = self.textView.frame;
////        textframe.size.width = kbFrame.size.width;
//        textframe.origin.y = kbFrame.origin.y - textframe.size.height;
//        self.textView.frame = textframe;
        [self.bottomBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).with.offset(-kbFrame.size.height);
        }];
    } completion:^(BOOL finished) {
        ;
    }];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    ;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    [self dismiss];
}
- (void)textViewDidChange:(UITextView *)textView {
    //    if (textView.frame.size.height > 90) {
    //        textView.scrollEnabled = YES;
    //    } else {
    //        textView.scrollEnabled = NO;
    //    }
//    CGFloat width = CGRectGetWidth(textView.frame);
//    CGSize size = [textView sizeThatFits:CGSizeMake(width, NSIntegerMax)];
//    if (size.height > 100) {
//        self.iTextViewHeightConstraint.constant = 100;
//    } else {
//        self.iTextViewHeightConstraint.constant = size.height;
//    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark - event response
- (void)sendBtnTapped:(UIButton *)btn {
    ;
}

#pragma mark - getters and setters
- (SZTextView *)textView {
    if (!_textView) {
        _textView = [[SZTextView alloc] init];
        _textView.layer.borderWidth = 1;
        _textView.layer.borderColor = [UIColor xd_colorWithHex:0xE7E7E7].CGColor;
        _textView.layer.masksToBounds = YES;
        _textView.layer.cornerRadius = 4;
        _textView.delegate = self;
        _textView.text = @"1231231313";
    }
    return _textView;
}

- (UIView *)bottomBgView {
    if (!_bottomBgView) {
        _bottomBgView = [[UIView alloc] init];
        _bottomBgView.backgroundColor = [UIColor xd_colorWithHex:0xF3F3F3];
    }
    return _bottomBgView;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = [UIColor xd_colorWithHex:0xE7E7E7];
    }
    return _lineView;
}

- (UIButton *)sendBtn {
    if (!_sendBtn) {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [_sendBtn addTarget:self action:@selector(sendBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

@end
